/******************************************************************
 * @Title: HomeController.java 
 * @Package com.omni.web.controllers 
 * @Description: TODO
 * @author Dellinger
 * @date 2015年4月22日 上午12:40:38 
 * @version v1.0 
 * @copyright Omnikennect.com
 ******************************************************************/
package com.omni.web.controllers;

import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.impl.JsonReadContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.omni.dao.TenantDAO;
import com.omni.dao.UserbaseDAO;
import com.omni.dao.clause.WhereClause;
import com.omni.dao.entry.Tenant;
import com.omni.dao.entry.Userbase;
import com.omni.web.model.JsonResult;
import com.omni.web.model.TeamModel;
import com.omni.web.utils.RoleUtil;
import com.omni.web.utils.TokenUtil;

/** 
 * @ClassName: HomeController 
 * @Description: TODO 
 * @author Dellinger
 * @date 2015年4月22日 上午12:40:38 
 *  
 */
@Controller
@RequestMapping("/home")
public class HomeController extends BaseController {

	private final static String DEFAULT_AVATAR = "/uploads/avatar/default.png";
	
	private UserbaseDAO userDAO;

	public void setUserDAO(UserbaseDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	private TenantDAO tenantDAO;
	
	public void setTenantDAO(TenantDAO tenantDAO) {
		this.tenantDAO = tenantDAO;
	}
	
	@RequestMapping(value = "/index", method=RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		
		return new ModelAndView("home/index");
	}
	
	@RequestMapping(value = "/login", method=RequestMethod.GET)
	public ModelAndView login() {
		
		return new ModelAndView("home/login");
	}

	@RequestMapping(value = "/login", method=RequestMethod.POST)
	public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) {

		ModelAndView ret = null;
		Map<String, String> map = new HashMap<String, String>();

		String user = request.getParameter("username");
		String pswd	= request.getParameter("password");
		String code = request.getParameter("verifycode");
		String scode = (String) getSession().getAttribute("CaptchaCode");
		
		if (StringUtils.isBlank(user)) {
			
			map.put("user", "不能为空！");
		}
		
		if (StringUtils.isBlank(pswd)) {
			map.put("password", "不能为空!");
		}
		
		if (StringUtils.isBlank(code)) {
			map.put("captcha", "验证码不能为空!");
		} else if (!scode.equalsIgnoreCase(code)) {
			map.put("captcha", "验证码不正确，请重新输入!");
		}
		
		
		//非空验证通过才做数据库校验
		if (map.size() < 1) 
		{
			List<Userbase> users = null;
			String colStr = "";
			//ToDo: Username can't be pure number("13424243234") or include '@' char;
			if(user.indexOf("@")>0){
				colStr = "email=?";	
			}else{
				
				if(StringUtils.isNumeric(user)){
					colStr = "phone=?";
				}else{
				    colStr = "username=?";
				}
			}
			users = userDAO.findAll(
						WhereClause.create().and(colStr, Types.VARCHAR, user),
						null, null);
			
			if (users == null || users.size() < 1 || !pswd.equals(users.get(0).getPassword())) {
				
				map.put("errors", "无效的用户名或密码！");
			} else {
				
				getSession().setAttribute(SESSION_KEY_AUTH, "1");
				getSession().setAttribute(this.SESSION_KEY_USER, users.get(0));
			}
		}
		
		if (map.size() > 0) {
			ret = new ModelAndView("home/login", map);
			ret.addObject("error", map);
			
		} else {
			ret = new ModelAndView("redirect:/chat/index");
			//TODO: add user profile info to model.
		}
		
		return ret;
	}

	@RequestMapping(value = "/register", method=RequestMethod.GET)
	public ModelAndView register() {
		
		return new ModelAndView("home/register");
	}
	
	@RequestMapping(value = "/join", method=RequestMethod.POST)
	public ModelAndView join(HttpServletRequest request, HttpServletResponse response) {
		
		
		String tname 	= request.getParameter("teamname");
		String temail	= request.getParameter("teamemail");
		String tpwd		= request.getParameter("teampwd");
		
		TeamModel model = new TeamModel();
		model.setName(tname);
		model.setEmail(temail);
		model.setPwd(tpwd);
		
		return new ModelAndView("home/activate", "model", model);
	}
	
	@RequestMapping(value = "/sms", method=RequestMethod.GET)
	@ResponseBody
	public JsonResult genMobileCode(HttpServletRequest request, HttpServletResponse response) {

		int token = TokenUtil.generateNumeric(100000, 999999);
		request.getSession().setAttribute("sms", String.valueOf(token));
		
		return new JsonResult(true, String.valueOf(token));
	}
	
	@RequestMapping(value = "/actsms", method=RequestMethod.POST)
	public ModelAndView activateSMS(HttpServletRequest request, HttpServletResponse response) {
		
		String phone = (String) request.getParameter("mobile");
		String val = (String) request.getParameter("actcode"); 
		String sms = (String) request.getSession().getAttribute("sms");
		
		if (!StringUtils.isBlank(sms) && sms.equals(val)) {
			
			String uname 	= request.getParameter("username");
			String password = request.getParameter("password");
			String email 	= request.getParameter("email");
			
			Userbase user = new Userbase();
			user.setUsername(uname);
			user.setNickname(uname);
			user.setAvatar(DEFAULT_AVATAR);
			user.setEmail(email);
			user.setPassword(password);
			user.setIslock(false);
			user.setRoleids(RoleUtil.parseRoles(new int[] { RoleUtil.ROLE_TEAMCREATOR }));
			user.setPhone(phone);
			user.setUsertype("1");
			user.setValidatedtype(1);
			user.setCreatedate(new Date());
			user.setUpdatedate(new Date());
			userDAO.save(user);
			
			Tenant tenant = new Tenant();
			tenant.setDomain(uname);
			tenant.setIsactive(true);
			tenant.setOwnerid(user.getId());
			tenant.setTname(uname);
			tenant.setTenanttype(1);
			tenant.setDesc("");
			tenant.setCreatedate(new Date());
			tenant.setUpdatedate(new Date());
			tenantDAO.save(tenant);
			
			getSession().setAttribute(SESSION_KEY_AUTH, "1");
			getSession().setAttribute(this.SESSION_KEY_USER, user);
			
			return new ModelAndView("redirect:/chat/index");
		}
		return new ModelAndView("home/activate");
		
	}
}
